count( ) Function
The count( ) Function is used to count, how many times a substring is present in the String.
x = "Hello Beautiful World" y = x.count("Beautiful") print("The count of the substring is ",y)
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be searching the substring 'Beautiful', and count how many times it is present in the String, 'Hello Beautiful World'.
So, we have used the 'count()' Function to count for the substring 'Beautiful'.
And in this case the substring 'Beautiful' is present just once. So, we got the count as 1.
And the count (i.e. 1) is stored in variable 'y'.
And thus prints the position.
Now, let us say you have the below String,
So there are two occurrence of 'Beautiful'.
Also let us specify the range as second and third paraemeter.
Let us see with the below example.
x = "The Beautiful world is Beautiful indeed" y = x.count("Beautiful", 1, 35) print("The count of the substring is ",y)
In the above code, we have declared a String 'The Beautiful world is Beautiful indeed' and assigned it to a variable 'x'.
And we would be searching the substring 'Beautiful', and count how many times it is present in the String, 'The Beautiful world is Beautiful indeed'.
So, we have used the 'x.count("Beautiful", 1, 35)' Function to count for the substring 'Beautiful'.
And also specified range of 1 to 35, to check how many times the substring 'Beautiful' is present in that range.
And in this case the substring 'Beautiful' is present twice. So, we got the count as 2.
And the count (i.e. 2) is stored in variable 'y'.
And thus prints the position.